package org.raymond.icloud.common.starter.listener;

import cn.hutool.core.lang.Assert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.listener.ListenerContainerConsumerFailedEvent;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Slf4j
@Component
public class ListenerContainerConsumerFailedEventListener implements ApplicationListener<ListenerContainerConsumerFailedEvent> {
    @Override
    public void onApplicationEvent(ListenerContainerConsumerFailedEvent event) {
        log.warn("Listen container consumer failed event.");
        if(event.isFatal()){
            SimpleMessageListenerContainer container = (SimpleMessageListenerContainer) event.getSource();
            String queueNames = Arrays.toString(container.getQueueNames());
            try{
                Thread.sleep(10*1000);
                try{
                    if(container.isRunning()){
                        container.stop();
                    }
                }catch (Exception e){
                    log.error("Stop ({}) failed!", queueNames);
                }

                Assert.state(!container.isRunning(), String.format("Container ({}) still running!", container));
                container.start();
            }catch (Exception e){
                log.error("Restart ({}) failed!", queueNames);
            }
        }
    }
}
